<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import {
  Button,
  Card,
  Col,
  DatePicker,
  Form,
  FormItem,
  Input,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
} from 'ant-design-vue';

const loading = ref(false);
const historyList = ref<any[]>([]);
const selectedRowKeys = ref<string[]>([]);

const searchForm = reactive({
  keyword: '',
  resourceType: '',
  businessType: '',
  status: '',
  dateRange: [],
});

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 资源类型选项
const resourceTypeOptions = [
  { label: '房间', value: 'ROOM' },
  { label: '设备', value: 'EQUIPMENT' },
  { label: '场地', value: 'VENUE' },
  { label: '车辆', value: 'VEHICLE' },
  { label: '人员', value: 'PERSONNEL' },
];

// 业务类型选项
const businessTypeOptions = [
  { label: '酒店', value: 'HOTEL' },
  { label: '公寓', value: 'APARTMENT' },
  { label: '温泉洗浴', value: 'HOT_SPRING' },
  { label: '餐饮', value: 'RESTAURANT' },
  { label: '宠物医疗', value: 'PET_MEDICAL' },
  { label: '医美', value: 'MEDICAL_BEAUTY' },
  { label: '培训班', value: 'TRAINING' },
];

// 状态选项
const statusOptions = [
  { label: '已完成', value: 'COMPLETED' },
  { label: '已取消', value: 'CANCELLED' },
  { label: '异常结束', value: 'ABNORMAL' },
];

// 表格列定义
const columns = [
  {
    title: '资源名称',
    dataIndex: 'resourceName',
    key: 'resourceName',
    width: 150,
  },
  {
    title: '业务类型',
    dataIndex: 'businessType',
    key: 'businessType',
    width: 120,
  },
  {
    title: '客户信息',
    dataIndex: 'customerInfo',
    key: 'customerInfo',
    width: 150,
  },
  {
    title: '占用时间',
    dataIndex: 'occupancyTime',
    key: 'occupancyTime',
    width: 200,
  },
  {
    title: '实际时长',
    dataIndex: 'actualDuration',
    key: 'actualDuration',
    width: 100,
  },
  {
    title: '使用费用',
    dataIndex: 'usageCost',
    key: 'usageCost',
    width: 120,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right' as const,
  },
];

// 加载历史数据
const loadHistory = async () => {
  loading.value = true;
  try {
    // 模拟历史数据
    const mockHistory = [
      {
        id: '1',
        resourceName: '标准客房101',
        resourceType: 'ROOM',
        businessType: 'HOTEL',
        customerInfo: '张先生 (138****8888)',
        startTime: '2024-03-14 14:00',
        endTime: '2024-03-15 12:00',
        occupancyTime: '2024-03-14 14:00 - 2024-03-15 12:00',
        actualDuration: '22小时',
        usageCost: 300,
        status: 'COMPLETED',
        bookingId: 'B001',
        notes: '正常退房',
      },
      {
        id: '2',
        resourceName: '会议室A',
        resourceType: 'VENUE',
        businessType: 'TRAINING',
        customerInfo: '培训部 (李老师)',
        startTime: '2024-03-14 09:00',
        endTime: '2024-03-14 17:00',
        occupancyTime: '2024-03-14 09:00 - 2024-03-14 17:00',
        actualDuration: '8小时',
        usageCost: 200,
        status: 'COMPLETED',
        bookingId: 'B002',
        notes: '培训课程',
      },
      {
        id: '3',
        resourceName: '按摩师张师傅',
        resourceType: 'PERSONNEL',
        businessType: 'HOT_SPRING',
        customerInfo: '王女士 (139****9999)',
        startTime: '2024-03-14 15:00',
        endTime: '2024-03-14 16:00',
        occupancyTime: '2024-03-14 15:00 - 2024-03-14 16:00',
        actualDuration: '1小时',
        usageCost: 100,
        status: 'COMPLETED',
        bookingId: 'B003',
        notes: '按摩服务',
      },
      {
        id: '4',
        resourceName: '投影设备',
        resourceType: 'EQUIPMENT',
        businessType: 'TRAINING',
        customerInfo: '培训部 (孙老师)',
        startTime: '2024-03-13 09:00',
        endTime: '2024-03-13 12:00',
        occupancyTime: '2024-03-13 09:00 - 2024-03-13 12:00',
        actualDuration: '3小时',
        usageCost: 50,
        status: 'CANCELLED',
        bookingId: 'B004',
        notes: '设备故障取消',
      },
      {
        id: '5',
        resourceName: '豪华套房201',
        resourceType: 'ROOM',
        businessType: 'HOTEL',
        customerInfo: '刘先生 (137****7777)',
        startTime: '2024-03-12 16:00',
        endTime: '2024-03-13 11:00',
        occupancyTime: '2024-03-12 16:00 - 2024-03-13 11:00',
        actualDuration: '19小时',
        usageCost: 500,
        status: 'COMPLETED',
        bookingId: 'B005',
        notes: '正常退房',
      },
    ];

    historyList.value = mockHistory;
    pagination.total = mockHistory.length;
  } catch (error) {
    console.error('加载历史数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  loadHistory();
};

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    keyword: '',
    resourceType: '',
    businessType: '',
    status: '',
    dateRange: [],
  });
  handleSearch();
};

// 查看详情
const viewDetail = (record: any) => {
  console.log('查看详情:', record);
  // 这里可以打开详情弹窗
};

// 导出数据
const exportData = () => {
  console.log('导出数据');
  // 这里可以实现数据导出功能
};

// 批量操作
const batchOperation = (operation: string) => {
  console.log('批量操作:', operation, selectedRowKeys.value);
  // 这里可以实现批量操作功能
};

// 辅助函数
const getBusinessTypeColor = (type: string) => {
  const colors = {
    HOTEL: 'blue',
    APARTMENT: 'green',
    HOT_SPRING: 'orange',
    RESTAURANT: 'purple',
    PET_MEDICAL: 'cyan',
    MEDICAL_BEAUTY: 'pink',
    TRAINING: 'geekblue',
  };
  return colors[type as keyof typeof colors] || 'default';
};

const getBusinessTypeLabel = (type: string) => {
  const labels = {
    HOTEL: '酒店',
    APARTMENT: '公寓',
    HOT_SPRING: '温泉洗浴',
    RESTAURANT: '餐饮',
    PET_MEDICAL: '宠物医疗',
    MEDICAL_BEAUTY: '医美',
    TRAINING: '培训班',
  };
  return labels[type as keyof typeof labels] || type;
};

const getStatusColor = (status: string) => {
  const colors = {
    COMPLETED: 'green',
    CANCELLED: 'red',
    ABNORMAL: 'orange',
  };
  return colors[status as keyof typeof colors] || 'default';
};

const getStatusLabel = (status: string) => {
  const labels = {
    COMPLETED: '已完成',
    CANCELLED: '已取消',
    ABNORMAL: '异常结束',
  };
  return labels[status as keyof typeof labels] || status;
};

onMounted(() => {
  loadHistory();
});
</script>

<template>
  <div class="occupancy-history">
    <!-- 搜索区域 -->
    <Card title="搜索条件" :bordered="false" style="margin-bottom: 16px">
      <Row :gutter="16">
        <Col :span="6">
          <Form.Item label="关键词">
            <Input
              v-model:value="searchForm.keyword"
              placeholder="请输入资源名称或客户信息"
              allow-clear
            />
          </Form.Item>
        </Col>
        <Col :span="6">
          <Form.Item label="资源类型">
            <Select
              v-model:value="searchForm.resourceType"
              placeholder="请选择资源类型"
              allow-clear
              :options="resourceTypeOptions"
            />
          </Form.Item>
        </Col>
        <Col :span="6">
          <Form.Item label="业务类型">
            <Select
              v-model:value="searchForm.businessType"
              placeholder="请选择业务类型"
              allow-clear
              :options="businessTypeOptions"
            />
          </Form.Item>
        </Col>
        <Col :span="6">
          <Form.Item label="状态">
            <Select
              v-model:value="searchForm.status"
              placeholder="请选择状态"
              allow-clear
              :options="statusOptions"
            />
          </Form.Item>
        </Col>
      </Row>
      <Row>
        <Col :span="24" style="text-align: right">
          <Space>
            <Button @click="resetSearch">重置</Button>
            <Button type="primary" @click="handleSearch">搜索</Button>
          </Space>
        </Col>
      </Row>
    </Card>

    <!-- 数据表格 -->
    <Card :bordered="false">
      <div class="table-toolbar">
        <Space>
          <Button
            :disabled="selectedRowKeys.length === 0"
            @click="batchOperation('export')"
          >
            <IconifyIcon icon="mdi:download" />
            批量导出
          </Button>
          <Button @click="exportData">
            <IconifyIcon icon="mdi:file-export" />
            导出全部
          </Button>
        </Space>
      </div>

      <Table
        :columns="columns"
        :data-source="historyList"
        :loading="loading"
        :pagination="pagination"
        :row-selection="{
          selectedRowKeys,
          onChange: (keys: any[]) => (selectedRowKeys = keys as string[]),
        }"
        row-key="id"
        size="middle"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'businessType'">
            <Tag :color="getBusinessTypeColor(record.businessType)">
              {{ getBusinessTypeLabel(record.businessType) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'usageCost'">
            ¥{{ record.usageCost.toLocaleString() }}
          </template>
          <template v-else-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusLabel(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="viewDetail(record)">
                详情
              </Button>
              <Button type="link" size="small"> 重新预约 </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>
  </div>
</template>

<style scoped>
.occupancy-history {
  padding: 20px;
}

.table-toolbar {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
